<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="专题名称">
                <a-input v-model="queryParam.search_key" placeholder="请输入专题名称" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator flex-y-center flex-x-sb">
        <a-radio-group v-model="tabsIndex" @change="onOptionChange">
          <a-radio-button :value="-1"> 全部 </a-radio-button>
          <a-radio-button :value="1"> 显示 </a-radio-button>
          <a-radio-button :value="0"> 不显示 </a-radio-button>
        </a-radio-group>

        <div>
          <a-button type="primary" @click="onAdd" icon="plus">添加</a-button>
          <a-popconfirm title="确认删除所选项吗？" @confirm="handleMenuClick">
            <a-button > 批量删除 </a-button>
          </a-popconfirm>
        </div>
      </div>

      <div v-show="selectedRowKeys.length" class="select-title">
        <a-alert :message="`已选择 ${selectedRowKeys.length} 项`" type="info" show-icon />
      </div>
      <s-table
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        rowKey="id"
        size="default"
        :columns="columns"
        :data="loadData"
        ref="table">
        <a-popconfirm
          placement="topLeft"
          slot="status"
          slot-scope="text, record"
          ok-text="确定"
          cancel-text="取消"
          @confirm="changeShow(record)"
        >
          <template slot="title">
            <p>{{ text == 1 ? '是否确定不显示' : '是否确定显示' }}</p>
          </template>
          <a-switch checked-children="开" un-checked-children="关" :checked="text == 1" />
        </a-popconfirm>
        <div slot="name" slot-scope="tect, record">
          <img :src="record.cover_pic" style="width: 50px; height: 50px; border-radius: 5px;display:inline-block" />
          <div style="display:inline-block;margin-left:10px;transform:translateY(10px)">
            <a-tooltip>
              <template slot="title">
                {{ record.title }}
              </template>
              <div style="color: black;width:200px;overflow:hidden;text-overflow: ellipsis;white-space: nowrap;">{{ record.title }}</div>
            </a-tooltip>
            <div>{{ record.type_name }}</div>
          </div>
          </a-row>
        </div>
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除该专题吗？" @confirm="handleDelete(record)">
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm>
        </span>
      </s-table>

      <a-modal
        :title="isNew ? '创建专题' : '编辑专题'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        :bodyStyle="{ height: '600px', overflow: 'auto' }"
        v-model="visible"
        @ok="handleOk"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" style="display: none" label="主键" hasFeedback>
            <a-input placeholder="主键" :disabled="!isNew" v-decorator="['id']" />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="专题名称" hasFeedback>
            <a-input
              placeholder="专题名称"
              v-decorator="['title', { rules: [{ required: true, message: '请填写专题名称' }] }]"
            />
          </a-form-item>

          <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="副标题" hasFeedback>
            <a-input
              placeholder="副标题"
              v-decorator="['sub_title', { rules: [{ required: true, message: '请填写副标题' }] }]"
            />
          </a-form-item> -->

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="布局方式"
            extra="小图模式建议封面图片大小：268×202，大图模式建议封面图片大小：702×350"
          >
            <a-radio-group v-decorator="['layout', { initialValue: 0 }]">
              <a-radio :value="0"> 小图模式 </a-radio>
              <a-radio :value="1"> 大图模式 </a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="封面图">
            <storage-select
              selectNum="1"
              type="image"
              :defaultValue="form_cover_pic"
              @onOk="
                (data) => {
                  this.form_cover_pic = data
                }
              "
            >
            </storage-select>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="海报分享图">
            <storage-select
              selectNum="1"
              type="image"
              :defaultValue="form_qrcode_pic"
              @onOk="
                (data) => {
                  this.form_qrcode_pic = data
                }
              "
            >
            </storage-select>
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="选择分类">
            <a-select
              v-decorator="['type', { rules: [{ required: true, message: '请选择分类' }] }]"
              placeholder="请选择分类"
            >
              <a-select-option v-for="(item, index) in type_list" :key="index" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否精选" extra="">
            <a-radio-group v-decorator="['is_chosen', { initialValue: 0 }]">
              <a-radio :value="0"> 不精选 </a-radio>
              <a-radio :value="1"> 精选 </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="虚拟阅读量"
            extra="手机端显示的阅读量=实际阅读量+虚拟阅读量"
          >
            <a-input-number placeholder="虚拟阅读量" v-decorator="['virtual_read_count', { initialValue: 0 }]" />
          </a-form-item>

          <!-- <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="虚拟收藏量"
            extra="手机端显示的收藏量=实际收藏量+虚拟收藏量"
          >
            <a-input-number placeholder="虚拟收藏量" v-decorator="['virtual_favorite_count', { initialValue: 0 }]" />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="虚拟点赞量"
            extra="手机端显示的收藏量=实际点赞量+虚拟点赞量"
          >
            <a-input-number placeholder="虚拟点赞量" v-decorator="['virtual_agree_count', { initialValue: 0 }]" />
          </a-form-item> -->

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
            <a-input-number placeholder="排序" v-decorator="['sort', { initialValue: 0 }]" />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否显示" extra="">
            <a-radio-group v-decorator="['is_show', { initialValue: 0 }]">
              <a-radio :value="0"> 不显示 </a-radio>
              <a-radio :value="1"> 显示 </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="专题详情">
            <WangEditor :autoFocus="true" :value="form_content" @change="onDescChange" v-decorator="['content', { rules: [{ required: true, message: '请输入视频详情' }] }]"></WangEditor>
            <!-- <a-textarea
              :rows="2"
              id="content"
              v-decorator="['content', { rules: [{ required: true, message: '请输入视频详情' }] }]"
            /> -->
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import pick from 'lodash.pick'
import { STable, WangEditor } from '@/components'
import { getPermission } from '@/api/auth'
import { getTopic, createTopic, editTopic, delTopic, editTopicShow, topicBatchDels } from '@/api/content'
import NoBorderRadio from '@/components/NoBorderRadio/NoBorderRadio'

const STATUS = {
  1: '显示',
  0: '不显示',
}

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '名称',
    dataIndex: 'name',
    width: '320px',
    scopedSlots: {
      customRender: 'name',
    },
  },
  {
    title: '是/否精选',
    dataIndex: 'is_chosen_text',
  },
  {
    title: '排序',
    dataIndex: 'sort',
    sorter: (a, b) => a.sort - b.sort,
  },
  {
    title: '布局方式',
    dataIndex: 'layout_text',
  },
  {
    title: '状态',
    dataIndex: 'is_show',
    scopedSlots: {
      customRender: 'status',
    },
  },
  {
    title: '操作',
    width: '150px',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]
export default {
  name: 'ArticleList',
  components: {
    STable,
    NoBorderRadio,
    WangEditor,
  },
  data() {
    return {
      tabsIndex: -1,
      selectedRowKeys: [],
      isNew: false,
      visible: false,
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 5,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 16,
        },
      },
      form: this.$form.createForm(this),
      // 表头
      columns,
      // 权限树
      permissionTree: [],
      // 已选择的权限
      selectedPermission: [],
      modalLoading: false,
      defaultCheckedKeys: [],
      statusSelectValue: {
        key: '1',
        label: '显示',
      },
      type_list: [],
      form_cover_pic: '',
      form_qrcode_pic: '',
      form_content: '',
      // 查询条件参数
      queryParam: {
        search_key: null,
        search_is_show: -1,
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        return getTopic(parameter)
          .then((res) => {
            console.log('getTopic', res)
            this.type_list = res.data.type_list
            return res.data
          })
          .catch((err) => {
            this.$message.error(err.message)
            this.$refs.table.localLoading = false
          })
      },
    }
  },
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
  },
  created() {
    getPermission({}).then((res) => {
      this.permissionTree = res.data
    })
  },
  activated() {
    this.$refs.table.refresh()
  },
  methods: {
    onSelectChange(val) {
      this.selectedRowKeys = val
    },
    onDescChange(content) {
      this.form.setFieldsValue({
        content: content,
      })
    },
    changeTab(val) {
      if (val == 2) {
        this.$router.push({ name: 'ProjectList' })
      }
    },
    onOptionChange({ target: { value: val } }) {
      console.log(val)
      this.queryParam.search_is_show = val
      this.selectedRowKeys = []
      this.$refs.table.refresh()
    },
    resetQueryParams() {
      Object.assign(this.queryParam, {
        search_key: null,
        search_is_show: -1,
      })
      this.$refs.table.refresh(true)
    },
    changeShow(item) {
      console.log(item)
      const hide = this.$message.loading('请求中...', 0)
      editTopicShow({
        key: item.id,
        is_show: item.is_show,
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('操作成功！')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.modalLoading = false
        })
    },
    handleEdit(record) {
      this.isNew = false
      this.visible = true
      record.layout = parseInt(record.layout)
      record.is_chosen = parseInt(record.is_chosen)
      record.is_show = parseInt(record.is_show)
      this.form_cover_pic = record.cover_pic
      this.form_qrcode_pic = record.qrcode_pic
      this.form_content = record.content
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(record, [
            'id',
            'title',
            // 'sub_title',
            'layout',
            'cover_pic',
            'qrcode_pic',
            'type',
            'is_chosen',
            'virtual_read_count',
            // 'virtual_favorite_count',
            // 'virtual_agree_count',
            'sort',
            'is_show',
            'content',
          ])
        )
      })
    },
    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          return false
        }
        Object.assign(values, {
          cover_pic: this.form_cover_pic,
          qrcode_pic: this.form_qrcode_pic,
          sub_title: '',
          virtual_favorite_count: 0,
          virtual_agree_count: 0,
        })
        console.log('🚀 ~ file: articleList.vue ~ line 416 ~ this.form.validateFields ~ values', values)

        this.modalLoading = true
        if (this.isNew) {
          createTopic(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                this.$message.success('专题创建成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        } else {
          editTopic(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                this.$message.success('专题编辑成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        }
      })
    },
    onAdd: function () {
      this.isNew = true
      this.visible = true
      this.form_cover_pic = ''
      this.form_qrcode_pic = ''
      this.defaultCheckedKeys = []
    },
    onTreeCheck: function (checkedKeys, info) {
      console.log('checkedKeys', checkedKeys)
      this.selectedPermission = checkedKeys
    },
    handleDelete: function (record) {
      const hide = this.$message.loading('删除中...', 0)
      delTopic({
        key: record.id,
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('专题删除成功！')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
          this.modalLoading = false
        })
    },
    async handleMenuClick() {
      if (!this.selectedRowKeys.length) return

      try {
        const res = await topicBatchDels({ id: this.selectedRowKeys, status: 1 })
        if (res.code != 0) throw res
        this.selectedRowKeys = []
        this.$refs.table.refresh()
        this.$message.success(res.msg)
      } catch (res) {
        this.$message.error(res.msg || '服务器出错')
      }
    },
  },
}
</script>

<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
</style>
